package com.example.consumptionrecords.config.shiro;


import com.example.consumptionrecords.exception.ExceptionHandler;
import jakarta.servlet.Filter;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 孙敬佳
 * 2024 \ 02 \ 25
 */

@Configuration
public class ShiroConfig {

	@Value("${spring.data.redis.host}")
	private String REDIS_HOST;

	@Value("${spring.data.redis.port}")
	private int REDIS_PORT;

	@Value("${spring.data.redis.password}")
	private String REDIS_PASSWORD;

	@Bean("userRealm")
	public Realm getUserRealm() {
		// 自定义用户名密码登录realm
		UserRealm userRealm = new UserRealm();
		userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
		return userRealm;
	}

	@Bean("phoneRealm")
	public Realm getPhoneRealm() {
		// 自定义手机号登录realm
		return new PhoneRealm();
	}

	@Bean
	public SecurityManager securityManager(@Qualifier("userRealm") Realm userRealm, @Qualifier("phoneRealm") Realm phoneRealm) {
		DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

		// 认证策略
		defaultWebSecurityManager.setAuthenticator(modularRealmAuthenticator());

		// 设置多realm
		defaultWebSecurityManager.setRealms(Arrays.asList(userRealm, phoneRealm));
//		defaultWebSecurityManager.setRealm(userRealm);

		// 自定义session管理
		defaultWebSecurityManager.setSessionManager(sessionManager());
//		// 自定义缓存实现 使用redis
		defaultWebSecurityManager.setCacheManager(redisCacheManager());

		return defaultWebSecurityManager;
	}

	@Bean
	public ShiroFilterFactoryBean shiroFilterFactory(SecurityManager securityManager) {
		// 配置拦截器
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		shiroFilterFactoryBean.setSecurityManager(securityManager);
		Map<String, Filter> filters = shiroFilterFactoryBean.getFilters();
		filters.put("authc", new UserFilter());
		shiroFilterFactoryBean.setFilters(filters);
		// 过滤器链
		Map<String, String> filterChain = new LinkedHashMap<>();
		filterChain.put("/user/login", "anon");
		filterChain.put("/user/accountPasswordLogin", "anon");
		filterChain.put("/user/phoneAuthCodeLogin", "anon");
		filterChain.put("/user/getAuthCode", "anon");
		filterChain.put("/user/register", "anon");
		filterChain.put("/login", "anon");
		filterChain.put("/**", "authc");
		// 登录接口
		shiroFilterFactoryBean.setLoginUrl("/user/unauthorized");
		// 加载过滤器链
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChain);
		return shiroFilterFactoryBean;
	}

	/**
	 * 密码匹配器
	 * @return hashedCredentialsMatcher
	 */
	@Bean
	public HashedCredentialsMatcher hashedCredentialsMatcher() {
		// 密码匹配算法
		HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
		hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
		hashedCredentialsMatcher.setHashIterations(2);//散列的次数，比如散列两次，相当于 md5(md5(""));
		return hashedCredentialsMatcher;
	}


	/**
	 * 自定义sessionManager
	 * @return
	 */
	@Bean
	public SessionManager sessionManager() {
		// 自定义的sessionManager
		com.example.consumptionrecords.config.shiro.SessionManager sessionManager = new com.example.consumptionrecords.config.shiro.SessionManager();
		// 会话超时时间 7天
//		sessionManager.setGlobalSessionTimeout(7 * 24 * 60 * 60 * 1000);
		// 开启定时清理失效会话
		sessionManager.setSessionValidationSchedulerEnabled(true);
		// 指定sessionId
		sessionManager.setSessionIdCookie(sessionIdCookie());
		// 是否允许将sessionId 放到 cookie 中
		sessionManager.setSessionIdCookieEnabled(true);
		// 是否允许将 sessionId 放到 Url 地址拦中
		sessionManager.setSessionIdUrlRewritingEnabled(false);
		// 使用redis缓存
		sessionManager.setSessionDAO(redisSessionDAO());
		return sessionManager;
	}

	/**
	 * 指定本系统sessionid, 问题: 与servlet容器名冲突, 如jetty, tomcat 等默认jsessionid,
	 * 当跳出shiro servlet时如error-page容器会为jsessionid重新分配值导致登录会话丢失!
	 *
	 * @return
	 */
	@Bean
	public SimpleCookie sessionIdCookie() {
		SimpleCookie simpleCookie = new SimpleCookie("shiro.session");
		// 防止xss攻击，窃取cookie内容
		simpleCookie.setHttpOnly(true);
		return simpleCookie;
	}

	/**
	 * 配置shiro redisManager
	 * 使用的是shiro-redis开源插件
	 *
	 * @return
	 */
	@Bean("redisManager")
	public RedisManager redisManager() {
		RedisManager redisManager = new RedisManager();
		redisManager.setHost(REDIS_HOST);
		redisManager.setPort(REDIS_PORT);
		redisManager.setPassword(REDIS_PASSWORD);
		redisManager.setExpire(7 * 24 * 60 * 60);// 配置缓存过期时间
//		redisManager.setExpire(5);// 配置缓存过期时间
		return redisManager;
	}

	/**
	 * cacheManager 缓存 redis实现
	 * 使用的是shiro-redis开源插件
	 *
	 * @return
	 */
	@Bean
	public RedisCacheManager redisCacheManager() {
		RedisCacheManager redisCacheManager = new RedisCacheManager();
		redisCacheManager.setRedisManager(redisManager());
		return redisCacheManager;
	}

	/**
	 * RedisSessionDAO shiro sessionDao层的实现 通过redis
	 * 使用的是shiro-redis开源插件
	 */
	@Bean
	public com.example.consumptionrecords.config.shiro.RedisSessionDAO redisSessionDAO() {
		com.example.consumptionrecords.config.shiro.RedisSessionDAO redisSessionDAO = new com.example.consumptionrecords.config.shiro.RedisSessionDAO();
		// 注入redisManager
		redisSessionDAO.setRedisManager(redisManager());
		// 设置session key前缀
		redisSessionDAO.setKeyPrefix("user_session_id_token:");
		return redisSessionDAO;
	}

	/**
	 * 开启shiro aop注解支持.
	 * 使用代理方式;所以需要开启代码支持;
	 *
	 * @param securityManager 安全管理器
	 * @return AuthorizationAttributeSourceAdvisor
	 */
	@Bean
	public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
		// 开启注解支持
		AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
		// 注入securityManager
		authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
		return authorizationAttributeSourceAdvisor;
	}

	@Bean
	public ModularRealmAuthenticator modularRealmAuthenticator() {
		com.example.consumptionrecords.config.shiro.ModularRealmAuthenticator modularRealmAuthenticator = new com.example.consumptionrecords.config.shiro.ModularRealmAuthenticator();
		// 多realm认证规则
		// AtLeastOneSuccessfulStrategy() 只要有一个认证成功则视为成功
		// FirstSuccessfulStrategy() 第一个认证成功整体视为成功，后续被忽略
		// AllSuccessfulStrategy() 所有认证成功才视为成功
		modularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
		return modularRealmAuthenticator;
	}

	/**
	 * 注册全局异常处理
	 * @return
	 */
	@Bean(name = "exceptionHandler")
	public HandlerExceptionResolver handlerExceptionResolver() {
		return new ExceptionHandler();
	}
}
